import time
import logging
from django.http import HttpRequest, HttpResponse

logging.basicConfig(filename='request_time.log', level=logging.INFO,
                    format='%(asctime)s - %(message)s')


class RequestTimeMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request: HttpRequest):
        # 记录请求开始时间
        start_time = time.time()

        # 调用 get_response 处理请求
        response = self.get_response(request)

        # 记录请求结束时间
        end_time = time.time()

        # 计算请求耗时
        request_time = end_time - start_time

        # 记录日志
        logging.info(f"请求 {request.path} 耗时: {request_time:.4f} 秒")

        return response
